package com.rongxue.controller.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rongxue.mapper.SAdvertisementMapper;
import com.rongxue.mapper.SIntegralMapper;
import com.rongxue.mapper.SUserDueDetailMapper;
import com.rongxue.mapper.SUserMapper;
import com.rongxue.pojo.*;
import com.rongxue.service.AdvertisementService;
import com.rongxue.service.Impl.CashInAndOutServiceImpl;
import com.rongxue.service.MobileCodeService;
import com.rongxue.service.SuserService;
import com.rongxue.service.UserAccountService;
import com.rongxue.service.BankBusinessService;
import com.rongxue.service.ProjectService;
import com.rongxue.service.utils.MobileUtil;
import com.rongxue.service.utils.RecordsUtils;
import com.rongxue.utils.CodeUtils;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 *
 */
@Controller
public class IndexController {

    @Autowired
    private SuserService sUserService;

    @Autowired
    private MobileCodeService mobileCodeService;

    @Autowired
    private BankBusinessService bankBusinessService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private AdvertisementService advertisementService;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private SAdvertisementMapper sAdvertisementMapper;

    @Autowired
    private SIntegralMapper sIntegralMapper;

    @Autowired
    private SUserMapper sUserMapper;

    @Autowired
    private SUserDueDetailMapper sUserDueDetailMapper;
    @Autowired
    RecordsUtils recordsUtils;

    /**
     * 登入
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/public/pwd_login", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult login(XMLBean xmlBean){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("mobile",xmlBean.getMobile());
        SUser user = sUserService.selectUserByMap(map);
        map.clear();
        if(user==null){
            map.put("loginTypeTip","该用户还未注册");
            return ObjectResult.build("0","该用户还未注册",map);
        }
        else{
            return sUserService.selectToLogin(xmlBean,user);
        }
    }

    /**
     * 注册
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/public/register", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult register(XMLBean xmlBean,HttpServletResponse response){

        response.setHeader("Access-Control-Allow-Origin", "*");

        return sUserService.insertToregist(xmlBean);

    }

    /**
     * 修改密码
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/public/forget_pwd", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult forget_pwd(XMLBean xmlBean){

        return sUserService.forget_pwd(xmlBean);

    }



    /**
     * 退出登录
     */
    @RequestMapping(value = "/public/logout", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult logout(){
        return ObjectResult.build("1","成功");
    }

    /**
     * 短信
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/public/sms_code", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult sms_code(XMLBean xmlBean, HttpServletRequest request,HttpServletResponse response){
        try {
            String ip = CodeUtils.getIpAddress(request);
            response.setHeader("Access-Control-Allow-Origin", "*");
            return  mobileCodeService.sms_code(xmlBean,ip);
        }catch (Exception e){
            e.printStackTrace();
            return  ObjectResult.build("0","短信发送失败");
        }
    }

    /**
     * token登入
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/userinfo", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult userinfo(XMLBean xmlBean){
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        if(xmlBean.getToken()!=null) {
            String userId = CommonUtils.decToken(xmlBean.getToken());
            map.put("userId", userId);
            SUser user = sUserService.selectUserByMap(map);
            if(user==null)return  ObjectResult.build("0","用户不存在");
            Integer is_bank = bankBusinessService.selectUserBankCoutByUserid(user.getId());

            data.put("id",user.getId());
            data.put("username",user.getUsername());
            data.put("mobile",user.getMobile());
            data.put("avatar",user.getAvatar());
            data.put("level",user.getLevel());
            data.put("invite",user.getInvite());
            data.put("is_bank",is_bank);
            data.put("card_no_auth",user.getCardNoAuth());

            return ObjectResult.build("1", "成功",data);
        }
        else {
            return ObjectResult.build("0","token不存在");
        }
    }

    /**
     * 首页
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/index")
    @ResponseBody
    public ObjectResult index(XMLBean xmlBean) throws IOException {
        Map<String, Object> map = new HashMap<String,Object>();
        List<SProject> sProjects = new ArrayList<>();
        //首页轮播图
        List<SAdvertisement> carousel = advertisementService.selectAdvertisementList();
        for(SAdvertisement sAdvertisement:carousel ){
            sAdvertisement.setImage(CashInAndOutServiceImpl.ADMIN_URL+sAdvertisement.getImage());
        }
        //首页菜单
//        String menu = "{\"menu\": [{\"title\": \"运营数据\",\"logo\": \"http://www.baoye365.com:8080/public/images/yunyingshuju_icon.png\",\"type\": 0,\"url\": \"http://www.baoye365.com:8080/zhangyin/index/html5/id/3\",\"ios_type\": \"\",\"android_type\": \"0\"}, {\"title\": \"关于我们\",\"logo\": \"http://www.baoye365.com:8080/public/images/liaojiewomen_icon.png\",\"type\": 0,\"url\": \"http://www.baoye365.com:8080/zhangyin/index/html5/id/8\",\"ios_type\": \"\",\"android_type\": \"0\"}, {\"title\": \"安全保障\",\"logo\": \"http://www.baoye365.com:8080/public/images/anquanbaozhang_icon.png\",\"type\": 0,\"url\": \"http://www.baoye365.com:8080/zhangyin/index/html5/id/1\",\"ios_type\": \"\",\"android_type\": \"0\"}, {\"title\": \"邀请好友\",\"logo\": \"http://www.baoye365.com:8080/public/images/yaoqinghaoyou_icon.png\",\"type\": 1,\"url\": \"\",\"ios_type\": \"InviteFriendController\",\"android_type\": \"1\"}]}";
//        JSONObject jsonObject = JSON.parseObject(menu);
//        map.put("menu",jsonObject.get("menu"));

        //首页推举标
        SProject sProject1 = projectService.selectProjectListLevel1();
        if(sProject1!=null){
            sProject1.setPreferential_new(sProject1.getNew_preferential().toString());
//            sProject1.setDuration(DateUtil.getDaysBetweenToDate(sProject1.getEndTime(),new Date()));
            sProjects.add(sProject1);

        }
        SProject sProject2 = projectService.selectProjectListLevel2();
        if(sProject2!=null){
            sProject2.setPreferential_new(sProject2.getNew_preferential().toString());
//            sProject2.setDuration(DateUtil.getDaysBetweenToDate(sProject2.getEndTime(),new Date()));
            sProjects.add(sProject2);
        }


        Integer total_people = sUserMapper.selectTotalPeople();//累计投资人数
        BigDecimal total_intervest = sUserDueDetailMapper.selectTotalIntervest();//累计投资额

        map.put("total_people",total_people+6791);
        map.put("total_intervest",total_intervest.add(new BigDecimal(2546134)));
        map.put("carousel",carousel);
        map.put("project",sProjects);
        map.put("app_name","杭州兴舟投资管理有限公司");
        return   ObjectResult.build("1","成功",map);
    }


    /**
     * 是否注册
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/public/is_register", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult is_register(XMLBean xmlBean){

        if(!MobileUtil.isMobileNumber(xmlBean.getMobile())){
            return ObjectResult.build("0","手机号错误");
        }

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("mobile",xmlBean.getMobile());
        try {
            SUser user = sUserService.selectUserByMap(map);
            if(user==null){
                return ObjectResult.build("1","未注册",1);

            }else {
                return ObjectResult.build("1","已注册",2);
            }
        }catch (Exception e){
            return ObjectResult.build("0","请求失败",0);
        }

    }

    /**
     * 首页
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/carousel")
    @ResponseBody
    public ObjectResult carousel(XMLBean xmlBean) throws IOException {
        List<SAdvertisement> carousel = advertisementService.selectAdvertisementList();
        for(SAdvertisement sAdvertisement:carousel ){
            sAdvertisement.setImage(CashInAndOutServiceImpl.ADMIN_URL+sAdvertisement.getImage());
        }
        return ObjectResult.build("1","成功",carousel);
    }


    /**
     * 邀请注册页面
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/regist")
    public ModelAndView regist(XMLBean xmlBean) {
        ModelAndView modelAndView = new ModelAndView("index");
        if(xmlBean.getInvite()!=null) {
            modelAndView.addObject("invite", xmlBean.getInvite());
        }
        return modelAndView;
    }

    /**
     * 渠道连接
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/qudao")
    public ModelAndView qudao(XMLBean xmlBean) {
        ModelAndView modelAndView = new ModelAndView("qudao");
        modelAndView.addObject("channel", xmlBean.getChannel());
        return modelAndView;
    }

    /**
     * 下载app
     * @param xmlBean
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/index/appDownload")
    public void appDownload(XMLBean xmlBean , HttpServletRequest request , HttpServletResponse response) throws IOException{

        String url = sUserMapper.selectChannelUrl(xmlBean.getChannel());

        response.sendRedirect(url);
    }

    /**
     * html5
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/html5/id/1")
    @ResponseBody
    public ModelAndView html1(XMLBean xmlBean,HttpServletResponse response) throws IOException{
        String content = sAdvertisementMapper.selectContentByid("1");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * html5
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/html5/id/2")
    @ResponseBody
    public ModelAndView html2(XMLBean xmlBean ,HttpServletResponse response) throws  IOException{
        String content = sAdvertisementMapper.selectContentByid("2");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * html5
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/html5/id/3")
    @ResponseBody
    public ModelAndView html3(XMLBean xmlBean, HttpServletResponse response) throws IOException{
        String content = sAdvertisementMapper.selectContentByid("3");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * html5
     * @return
     */
    @RequestMapping(value = "/index/html5/id/4")
    @ResponseBody
    public ModelAndView html4(){
        ModelAndView modelAndView = new ModelAndView("qiandao");
        return modelAndView;
    }
    /**
     * html5
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/html5/id/5")
    @ResponseBody
    public ModelAndView html5(XMLBean xmlBean,HttpServletResponse response) throws IOException{
        String content = sAdvertisementMapper.selectContentByid("5");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * html5
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/html5/id/6")
    @ResponseBody
    public ModelAndView html6(XMLBean xmlBean,HttpServletResponse response) throws IOException{
        String content = sAdvertisementMapper.selectContentByid("6");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * html5
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/html5/id/7")
    @ResponseBody
    public ModelAndView html7(XMLBean xmlBean,HttpServletResponse response) throws  IOException{
        String content = sAdvertisementMapper.selectContentByid("7");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * html5
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/html5/id/8")
    @ResponseBody
    public ModelAndView html8(XMLBean xmlBean,HttpServletResponse response) throws IOException{
        String content = sAdvertisementMapper.selectContentByid("8");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * html5
     * @param xmlBean
     * @return
     *
     */
    @RequestMapping(value = "/index/html5/id/9")
    @ResponseBody
    public ModelAndView html9(XMLBean xmlBean,HttpServletResponse response) throws IOException{
        String content = sAdvertisementMapper.selectContentByid("9");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }

    /**
     * html5
     * @param xmlBean
     * @return
     *
     */
    @RequestMapping(value = "/index/html5/id/10")
    @ResponseBody
    public ModelAndView html10(XMLBean xmlBean,HttpServletResponse response) throws IOException{
        String content = sAdvertisementMapper.selectContentByid("10");
        if(content.contains("src")&content.contains("jpg")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".jpg") + 4));
            return null;
        }
        if(content.contains("src")&content.contains("png")){
            response.sendRedirect(content.substring(content.lastIndexOf("http"), content.lastIndexOf(".png") + 4));
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg",StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }
    /**
     * 广告详情
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/index/banner_ext")
    @ResponseBody
    public ModelAndView banner_ext(XMLBean xmlBean){
        String content = sAdvertisementMapper.selectExtById(xmlBean.getId());
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }


    /**
     * 动态详情
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/News/detail2")
    @ResponseBody
    public ModelAndView detail2(XMLBean xmlBean) {
        String content = sAdvertisementMapper.selectNewsDetail(xmlBean.getId());
        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", StringEscapeUtils.unescapeHtml4(content));
        return modelAndView;
    }

    @RequestMapping(value = "/News/detail")
    @ResponseBody
    public ObjectResult detail(XMLBean xmlBean) {
        String content = sAdvertisementMapper.selectNewsDetail(xmlBean.getId());
        Map<String,Object> map =new HashMap<>();
        map.put("content",StringEscapeUtils.unescapeHtml4(content));
        return   ObjectResult.build("1","成功",map);
    }

    /**
     * 动态
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/News/get_list")
    @ResponseBody
    public ObjectResult get_list(XMLBean xmlBean) {
        List<SNews> sNews = sAdvertisementMapper.selectNews();
        Page<SNews> page = new Page<>();
        page.setP(xmlBean.getP());
        page.setPageSize(10d);
        List<SNews> pageContent = page.getPageContent(sNews);
        for (SNews s:pageContent){
            s.setTime(s.getTime().substring(0,s.getTime().indexOf(".")));
            s.setImage(CashInAndOutServiceImpl.ADMIN_URL+s.getImage());
        }
        Map<String,Object> map =new HashMap<>();


        List<SNews> aaa = new ArrayList<>();
        map.put("count",page.getPageTotal());
        map.put("list",pageContent);
        return ObjectResult.build("1","成功",map);
    }

    /**
     * 福利中心顶部页面
     * @param xmlBean
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/ActivityAward/top_img")
    @ResponseBody
    public ObjectResult top_img(XMLBean xmlBean) throws IOException {
        if("".equals(xmlBean.getToken())||xmlBean.getToken()==null) return ObjectResult.build("0","未登录");
        String userId = CommonUtils.decToken(xmlBean.getToken());

        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("resource/interest.properties"));//获取配置文件
        String top_img = new String(properties.getProperty("top_img").getBytes("ISO-8859-1"));
        JSONObject jsonObject = JSON.parseObject(top_img);

        return ObjectResult.build("1","成功",jsonObject.get("top_img"));

    }

    /**
     * 福利中心
     * @param xmlBean
     * @return
     * @throws IOException
     */

    @RequestMapping(value = "/ActivityAward/get_list")
    @ResponseBody
    public ObjectResult award_get_list(XMLBean xmlBean) throws IOException {
        if("".equals(xmlBean.getToken())||xmlBean.getToken()==null) return ObjectResult.build("0","未登录");
        String userId = CommonUtils.decToken(xmlBean.getToken());

        //获取配置文件
        Map<String,Object> map =new HashMap<>();
        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("resource/interest.properties"));//获取配置文件
        String list = new String(properties.getProperty("list").getBytes("ISO-8859-1"));
        JSONObject jsonObject = JSON.parseObject(list);

        map.put("time",DateUtil.formatDate() + " 00:00:00");
        map.put("userId",userId);

        Integer sgin = sIntegralMapper.selectIntegralToday(map);
        SUser user = sUserService.selectUserByMap(map);
        map.clear();

        map.put("sign",sgin);//0 未签到 1 已签到
        map.put("realNameAut",user.getRealNameAuth());//0：未实名 1：已实名'
        map.put("list",jsonObject.get("list"));
        return ObjectResult.build("1","成功",map);
    }


    @RequestMapping(value = "/index/h5")
    public ModelAndView h5(XMLBean xmlBean) {
        ModelAndView modelAndView = new ModelAndView(xmlBean.getTitle());
        return modelAndView;
    }

    @RequestMapping(value = "/index/resultHtml")
    public ModelAndView resultHtme(XMLBean xmlBean) throws UnsupportedEncodingException {
        ModelAndView modelAndView =null ;
        if (xmlBean.getType()==0){
            modelAndView = new ModelAndView("pay_wrong");
        }
        else if (xmlBean.getType()==1){
            modelAndView = new ModelAndView("pay_success");
        }
        String  title = "";
        switch (xmlBean.getTitle()){
            case  "1" : title="充值成功"; break;
            case "2" : title = "充值失败"; break;
            case  "3" : title="提现成功"; break;
            case "4" : title = "提现失败"; break;
            case  "5" : title="开户成功"; break;
            case "6" : title = "开户失败"; break;
            case  "7" : title="出借成功"; break;
            case "8" : title = "出借失败"; break;
            case  "9" : title="签约成功"; break;
            case "10" : title = "签约失败"; break;
        }
        modelAndView.addObject("title",title);
        modelAndView.addObject("msg","");
        return modelAndView;
    }
}
